<template>
  <div class="box">
    <div class="time-select" :style="`margin-left:${type==1?40:0}px;margin-right:${type==1?0:20}px`">
      <div
        class="time-select-item"
        :class="{ active: index == selectIndex }"
        v-for="(item, index) in list"
        :key="index"
        @click="selectToggle(index)"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default () {
        return [
          {
            value: '1',
            name: '昨日'
          },
          {
            value: '30',
            name: '近30天'
          },
          {
            value: '183',
            name: '近半年'
          },
          {
            value: '365',
            name: '近一年'
          }
        ]
      }
    },
    type: {
      type: [String, Number],
      default: 1
    }
  },
  data () {
    return {
      selectIndex: 0
    }
  },
  methods: {
    selectToggle (index) {
      this.selectIndex = index
      console.log(this.getDay(this.list[index].value))
      if (this.type == 1) {
        this.$emit('timeChange', [
          this.getDay(this.list[index].value),
          this.getDay(0)
        ])
      } else {
        this.$emit('timeChange', this.list[index].value)
      }
    },
    getDay (day) {
      const today = new Date()
      const targetDay = today.getTime() - 1000 * 60 * 60 * 24 * day
      today.setTime(targetDay)
      const tYear = today.getFullYear()
      const tMonth = this.doHanldeMonth(today.getMonth() + 1)
      const tDay = this.doHanldeMonth(today.getDate())
      return tYear + '/' + tMonth + '/' + tDay
    },
    doHanldeMonth (month) {
      let m = month
      if (month.toString().length == 1) {
        m = '0' + month
      }
      return m
    }
  }
}
</script>

<style lang="less" scoped>
.time-select {
  display: flex;
  height: 32px;
  line-height: 30px;
  &-item {
    min-width: 75px;
    text-align: center;
    background: #fff;
    border: 1px solid #e3e2e5;
    border-right: none;
    cursor: pointer;
  }
  &-item:nth-child(1) {
    border-radius: 4px 0 0 4px;
  }
  &-item:nth-last-child(1) {
    border-radius: 0 4px 4px 0;
    border-right: 1px solid #e3e2e5;
  }
  &-item.active {
    color: #4393F2;
    border: 1px solid #4393F2;
  }
}
</style>
